﻿namespace IBTrader.Modules.Binarize
{
    using NLog;
    using System;
    using System.Globalization;
    using System.IO;
    using System.Linq;

    abstract class Binarizer : IBinarizer
    {
        private static readonly Logger logger = LogManager.GetCurrentClassLogger();
        protected static readonly CultureInfo ci = CultureInfo.InvariantCulture;
        protected abstract void WriteLine(BinaryWriter writer, string [] parts);
        public void BinarizeDirectory(string directory)
        {
            new DirectoryInfo(directory).GetFiles().AsParallel().ForAll(fileInfo => BinarizeFile(fileInfo));
        }
        public void BinarizeFile(FileInfo txt)
        {
            var bin = new FileInfo(Path.ChangeExtension(txt.FullName, "bin"));
            if (bin.Exists) return;
            try
            {
                using (var writer = new BinaryWriter(bin.Create()))
                    using (var reader = new StreamReader(File.Open(txt.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)))
                        while (!reader.EndOfStream)
                            WriteLine(writer, reader.ReadLine().Split(';'));
            }
            catch (Exception ex)
            {
                logger.ErrorException(ex.Message, ex);
                bin = new FileInfo(bin.FullName);
                if (bin.Exists)
                    bin.Delete();
            }
        }
    }
}